<script>
import { h } from "vue";
import ques from "./quesComponents.js";
export default {
	mixins: [ques],
	name: "HorzBlankQuestion",
	computed: {
		segments() {
			const content = this.question?.attribute?.content || "";
			// 使用正则表达式匹配，符合表单设计时存储的数据格式，否则校验无法匹配
			const regex = /<span\s+data-id="([^"]+)"\s+contenteditable="false">.*?<\/span>/g;
			const segments = [];
			let lastIndex = 0;
			let match;
			while ((match = regex.exec(content)) !== null) {
				if (match.index > lastIndex) {
					segments.push({ type: "text", text: content.slice(lastIndex, match.index) });
				}
				segments.push({ type: "input", id: match[1] });
				lastIndex = regex.lastIndex;
			}
			if (lastIndex < content.length) {
				segments.push({ type: "text", text: content.slice(lastIndex) });
			}
			return segments;
		}
	},
	methods: {
		isFinished() {
			return (
				this.question?.answer &&
				Object.values(this.question.answer).every((e) => {
					return e;
				})
			);
		}
	},
	render() {
		// 渲染解析后的文本和输入框
		const segmentNodes = this.segments.map((seg, index) => {
			if (seg.type === "text") {
				return seg.text;
			} else if (seg.type === "input") {
				if (!this.question.answer) {
					this.question.answer = {};
				}
				const currentValue = this.question?.answer?.[seg.id] || "";
				const i = h("i", {
					contentEditable: true,
					textContent: currentValue,
					onBlur: (e) => {
						this.question.answer[seg.id] = e.target.innerText.trim();
					}
				});
				return h("span", [i]);
			}
		});
		const titleNode = this.question.title ? h("div", { class: "ques-opt-title" }, [this.question?.attribute?.required ? h("i", { class: "star" }, "") : null, this.index + 1 + "、", this.question.title, !this.isValid && h("i", { class: "required-err-msg" }, "必填")]) : null;
		// 构造组件内容
		const children = [titleNode, h("div", { class: "ques-opt-body horz-blank" }, segmentNodes)].filter(Boolean);

		return h("div", children);
	}
};
</script>
